package com.sauro.common.util;


import lombok.SneakyThrows;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;

/**
 * 实践工具类
 *
 * @author liuxk
 * @date 2022/12/15
 */
public final class DateUtils {

    /**
     * 格式化到秒
     */
    public static final String FORMAT_S = "yyyy-MM-dd HH:mm:ss";

    /**
     * 格式化到天
     */
    public static final String FORMAT_D = "yyyy-MM-dd";

    public static final String FORMAT_M = "yyyyMM";

    /**
     * 一天有多少毫秒
     */

    public static final int ONE_DAY = 1000 * 60 * 60 * 24;
    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM",
            "yyyyMMdd", "yyyyMMddHHmmss", "yyyyMM"
    };

    /**
     * 私有构造
     */
    private DateUtils() {
    }

    /**
     * 转换Timestamp为字符串
     *
     * @return
     */
    public static String getTimestamp() {
        return (new Timestamp(System.currentTimeMillis())).toString();
    }

    public static Timestamp getTimestamp(int hour) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(System.currentTimeMillis());
        cal.set(Calendar.HOUR_OF_DAY, hour);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        Timestamp time = new Timestamp(System.currentTimeMillis());
        time.setTime(cal.getTimeInMillis());
        return time;
    }

    //得到当前的月数
    public static Date getNowDateMMYY() throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMM");
        Calendar c = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        return sdf.parse(df.format(c.getTime()));
    }

    /**
     * 日期型字符串转化为日期 格式
     *
     * @param str 日期字符串
     * @return
     */
    public static Date parseAllDate(String str) {
        if (str == null) {
            return null;
        }
        try {
            return org.apache.commons.lang3.time.DateUtils.parseDate(str, parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取两个日期相差的天数.
     *
     * @return 两个日期相差的天数.
     */
    public static int days(Date sdate, Date edate) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(sdate);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(edate);
        if (!cal1.before(cal2)) {
            int nBase = (cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR)) * 365;
            return (nBase + cal1.get(Calendar.DAY_OF_YEAR)) - cal2.get(Calendar.DAY_OF_YEAR);
        } else {
            return minus(cal2, cal1);
        }
    }

    /**
     * 获取两个日期相差的天数.
     *
     * @return 两个日期相差的天数.
     */
    public static int minus(Calendar cal1, Calendar cal2) {
        if (!cal1.before(cal2)) {
            int nBase = (cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR)) * 365;
            return (nBase + cal1.get(Calendar.DAY_OF_YEAR)) - cal2.get(Calendar.DAY_OF_YEAR);
        } else {
            return minus(cal2, cal1);
        }
    }

    public static int compare(Date date1, Date date2) {
        return date1.compareTo(date2);
    }

    /**
     * @param date1 <String>
     * @param date2 <String>
     * @return int
     * @throws ParseException
     */
    public static int getMonthSpace(String date1, String date2) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        int result = 0;
        Calendar cal1 = new GregorianCalendar();
        cal1.setTime(sdf.parse(date1));
        Calendar cal2 = new GregorianCalendar();
        cal2.setTime(sdf.parse(date2));
        result = (cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR)) * 12 + cal1.get(Calendar.MONTH) - cal2.get(Calendar.MONTH);
        return result == 0 ? 1 : Math.abs(result);

    }

    /**
     * 获取格式化后的时间yyyyMM
     */
    public static String getTimeYm(Date date) {
        SimpleDateFormat df = new SimpleDateFormat(FORMAT_M);
        return df.format(date);
    }

    /**
     * 增加或者减少月数
     *
     * @param
     * @return
     */
    public static String reduceMonth(int reduceMonth) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.MONTH, -reduceMonth);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        return sdf.format(cal.getTime());
    }


    public static String getTimeYear(String date) throws ParseException {
        Date date1 = StringToDateyyyMM(date);
        SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月");
        return df.format(date1);
    }

    public static Date StringToDate(String date) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date time = sdf.parse(date);
        return time;
    }

    public static Date StringToDateyyyMM(String date) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        Date time = sdf.parse(date);
        return time;
    }


    /**
     * 组织时间
     *
     * @param time
     * @return
     */
    public static String setTime(String time) {
        Calendar calendar = GregorianCalendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        String po = calendar.get(Calendar.YEAR) + "-0"
                + (calendar.get(Calendar.MONTH) + 1) + "-"
                + calendar.get(Calendar.DATE) + " ";
        return (po + time);
    }

    /**
     * 将传入的Timestamp 转换为字符串
     *
     * @param timestamp
     * @return String 的字符串
     */
    public static String getTime(Timestamp timestamp) {

        SimpleDateFormat format = new SimpleDateFormat(FORMAT_S);
        String date = format.format(timestamp.getTime());

        return date;
    }


    /**
     * 将传入的Timestamp 转换为字符串
     *
     * @param timestamp
     * @return String 的字符串
     */
    public static String getTimeYYYYMM(Timestamp timestamp) {

        SimpleDateFormat format = new SimpleDateFormat(FORMAT_M);
        String date = format.format(timestamp.getTime());

        return date;
    }

    /**
     * 将传入的Timestamp 转换为字符串
     *
     * @param timestamp
     * @return String 的字符串
     */
    public static String getTime(Timestamp timestamp, String fmat) {

        SimpleDateFormat format = new SimpleDateFormat(fmat);
        String date = format.format(timestamp.getTime());

        return date;
    }

    /**
     * 根据输入的值计算出下次时间
     *
     * @param timeValue
     * @return
     */
    public static String getNextTime(long timeValue) {
        long time = new Timestamp(System.currentTimeMillis()).getTime();
        long tmp = time + timeValue * 60 * 60 * 1000;
        return fromLongToDateString(tmp);
    }

    /**
     * 获取yi天时间
     *
     * @param str
     * @return
     * @throws ParseException
     */
    public static Date getDate(Timestamp str) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat(FORMAT_D);
        String st = format.format(str);
        Date date = format.parse(st);
        return date;
    }

    @SneakyThrows
    public static String yyyyMMddTurnyyyyMM(String yyyyMMdd) {
        SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat df = new SimpleDateFormat("yyyyMM");
        Date date = df2.parse(yyyyMMdd);
        return df.format(date);
    }

    /**
     * 获取yi天时间
     *
     * @param str
     * @return
     * @throws ParseException
     */
    public static Date getDateTime(Timestamp str) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat(FORMAT_S);
        String st = format.format(str);
        Date date = format.parse(st);
        return date;
    }


    /**
     * 此方法计算时间毫秒
     *
     * @param inVal
     * @return
     */
    public static long fromDateStringToLong(String inVal) {
        Date date = new Date(); // 定义时间类型
        SimpleDateFormat inputFormat = new SimpleDateFormat(FORMAT_S);
        try {
            // String st = inputFormat.format(inVal);
            date = inputFormat.parse(inVal); // 将字符型转换成日期型
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date.getTime();// 返回毫秒数
    }

    /**
     * 将毫秒数换算成String
     *
     * @param ms
     * @return
     */
    public static String fromLongToDateString(long ms) {
        SimpleDateFormat inputFormat = new SimpleDateFormat(FORMAT_S);
        return inputFormat.format(ms);

    }

    /**
     * 将毫秒数换算成String
     *
     * @param ms
     * @return
     */
    public static String fromLongToString(long ms) {
        SimpleDateFormat inputFormat = new SimpleDateFormat(FORMAT_D);
        return inputFormat.format(ms);

    }

    /**
     * 判断获取用户最后一次登出时间和目前的时间的时间差是否大于30天
     *
     * @param currTime   当前时间
     * @param logoutTime 退出时间
     * @return
     */
    public static boolean sumPlayerOnlineTime(long currTime, long logoutTime) {

        // 计算玩家没上线时间，最后将时间转化为以天为单位
        double notOnlineTime = (double) (currTime - logoutTime)
                / (1000 * 3600 * 24);//

        if (notOnlineTime >= 15) {
            return true;
        }
        return false;
    }

    /**
     * 获取系统当前时间
     *
     * @return
     */
    public static String getCurrTime() {
        SimpleDateFormat simpleDateTimeFormat = new SimpleDateFormat(FORMAT_S);
        return simpleDateTimeFormat.format(System.currentTimeMillis());
    }

    /**
     * 字符串转为时间格式
     *
     * @param str
     * @return
     * @throws ParseException
     */
    public static String getStrTimeToDay(String str) throws ParseException {
        DateFormat format = new SimpleDateFormat(FORMAT_D, Locale.CHINESE);
        String date = format.format(format.parse(str));

        return date;
    }


    /**
     * 字符串转为时间格式
     *
     * @param str
     * @return
     * @throws ParseException
     */
    public static String getStrTime(String str) throws ParseException {
        DateFormat format = new SimpleDateFormat(FORMAT_S, Locale.CHINESE);
        String date = format.format(format.parse(str));

        return date;
    }

    /**
     * 获取当前时间
     */
    public static String getTime() {
        Date date = Calendar.getInstance().getTime();
        SimpleDateFormat df = new SimpleDateFormat(FORMAT_S + ":SSS", Locale.US);
        return df.format(date);
    }

    /**
     * 获取格式化后的时间
     */
    public static String getTime(Date date) {
        SimpleDateFormat df = new SimpleDateFormat(FORMAT_S, Locale.US);
        return df.format(date);
    }

    /**
     * 获取格式化后的时间
     */
    public static String getTime(Date date, String format) {
        try {
            SimpleDateFormat df = new SimpleDateFormat(format, Locale.US);
            return df.format(date);
        } catch (Exception e) {
            return null;
        }
    }

    public static String getTimeUnknownFormat(Date date) {
        String str = "";
        try {
            str = getTime(date);
        } catch (Exception e) {
            str = getTime(date, FORMAT_D);
        }
        return str;
    }

    /**
     * 根据时间格式获取当前时间
     */
    public static String getTime(String format) {
        Date date = Calendar.getInstance().getTime();
        SimpleDateFormat df = new SimpleDateFormat(format, Locale.US);
        return df.format(date);
    }

    /**
     * 比较两时间的大小
     *
     * @param time1 时间1
     * @param time2 时间2
     * @return 0：time1相等time2；<br>
     * 1：time1大于time2；<br>
     * -1：time1小于time2；<br>
     */
    public static int isDateBefore(String time1, String time2) {
        SimpleDateFormat df = new SimpleDateFormat(FORMAT_S, Locale.US);
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        try {
            c1.setTime(df.parse(time1));
            c2.setTime(df.parse(time2));
        } catch (ParseException e) {
            return 0;
        }
        int result = c1.compareTo(c2);
        return result;
    }

    /**
     * 本周一
     *
     * @return the thisMonday
     */
    public static Date getThisMonday() {
        Calendar cal = Calendar.getInstance();
        // 默认时，每周第一天为星期一需要更改一下
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_D);
        String temp = sdf.format(cal.getTime());
        try {
            Date first = new Date(sdf.parse(temp + " 00:00:00").getTime());
            return first;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 本月一号
     *
     * @return the thisJanuary
     */
    @SneakyThrows
    public static Date getThisJanuary() {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String temp = sdf.format(cal.getTime());
        return new Date(sdf.parse(temp + "-01 00:00:00").getTime());
    }

    /**
     * 当月一号
     *
     * @return the thisJanuary
     */
    public static String getJanuary(Date time) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String temp = sdf.format(cal.getTime());
        String substring = temp.substring(7, 11);
        String replace = temp.replace(substring, "-01 ");
        try {
            long time1 = sdf.parse(replace + "-01 00:00:00")
                    .getTime();
            return time1 + "";
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 返回两时间段隔的天数
     *
     * @param time1 开始时间
     * @param time2 结束时间
     * @return
     * @throws Exception
     */
    public static int getDays(String time1, String time2) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_D);
        Date date1 = sdf.parse(time1);
        Date date2 = sdf.parse(time2);
        Calendar nowDate = Calendar.getInstance(), oldDate = Calendar.getInstance();
        nowDate.setTime(date1);
        oldDate.setTime(date2);
        long timeNow = nowDate.getTimeInMillis();
        long timeOld = oldDate.getTimeInMillis();
        int days = (int) ((timeOld - timeNow) / (ONE_DAY));
        return days;
    }

    /**
     * 把字符串格式化为日期格式
     * <p>
     * 把字符串格式化为日期格式
     * </p>
     *
     * @param dateStr
     * @return
     */
    public static Date parseStringToDate(String dateStr) {
        SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_D);
        try {
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            return null;
        }
    }

    public static Date parseStringMMToDate(String dateStr) {
        SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_M);
        try {
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 把字符串格式化为日期格式
     * <p>
     * 把字符串格式化为日期格式
     * </p>
     *
     * @param dateStr
     * @return
     */
    public static Date parseStringToDate2(String dateStr) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        try {
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 根据s身份证获取日期类型
     * @param dateStr
     * @return
     */
/*
	public static Date strChangeDate(String dateStr) {
		StringBuffer stringBuffer = new StringBuffer().append(dateStr.substring(6, 10) + "/").append(dateStr.substring(10, 12) + "/").append(dateStr.substring(12, 14));		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		try {
			return sdf.parse(stringBuffer+"");
		} catch (ParseException e) {
			return null;
		}
	}

*/

    /**
     * 把字符串格式化为日期格式
     * <p>
     * 把字符串格式化为日期格式
     * </p>
     *
     * @param dateStr
     * @return
     */
    public static Date parseStringToDate3(String dateStr) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        try {
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 把字符串格式化为日期格式带时分秒<br/>
     * <p>
     * 把字符串格式化为日期格式带时分秒
     * </p>
     *
     * @param dateStr
     * @return
     */
    public static Date parseStringToDateTime(String dateStr) {
        SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_S);
        try {
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            return null;
        }
    }
//	public static Date parseStringToDateTimeMMYYDD(String dateStr) {
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMDD");
//		try {
//			return sdf.parse(dateStr);
//		} catch (ParseException e) {
//			return null;
//		}
//	}

    /**
     * 把字符串格式化为日期格式带时分秒<br/>
     * <p>
     * 把字符串格式化为日期格式带时分秒
     * </p>
     *
     * @param dateStr
     * @return
     */
    public static Date parseStringToFORMAT_D(String dateStr) {
        SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_D);
        try {
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            return null;
        }
    }


    /**
     * 比较两个日期大小
     * <p>
     * 比较两个日期大小，日期格式为yyyy-MM-dd
     * </p>
     *
     * @param date1
     * @param date2
     * @return 0:相同
     * 1:date1>date2
     * -1:date1<date2
     */
    public static int compareDate(String date1, String date2) {
        int resultNum = 0;
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date d1 = df.parse(date1);
            Date d2 = df.parse(date2);
            if (d1.getTime() > d2.getTime()) {
                resultNum = 1;
            } else if (d1.getTime() < d2.getTime()) {
                resultNum = -1;
            } else {
                resultNum = 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultNum;
    }

    /**
     * 指定日期加上天数得到指定格式的日期
     *
     * @param begintime yyyy-MM-dd格式
     * @param deadline  天数 例如：1
     * @return
     */
    public static String dateAdd(String begintime, String deadline) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String newDate = "";
        try {
            Date d = df.parse(begintime);
            newDate = df.format(d.getTime() + Long.parseLong(deadline) * 24 * 60 * 60 * 1000);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return newDate;
    }

    /**
     * 比较证书有效截止日期是否大于今天
     *
     * @param begintime
     * @param deadline
     * @return
     */
    public static boolean isLaterThanCurrentDate(String begintime, String deadline) {
        boolean b = false;
        Date d = null;
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {
            d = df.parse(begintime);
            long time = d.getTime();
            long day = Long.parseLong(deadline) * 86400000;
            long newDate = time + day;
            long currentDate = new Date().getTime();
            if (newDate >= currentDate) {
                b = true;
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return b;
    }

    /**
     * 判断新时间是否大于旧时间
     * <p>
     * 判断新时间是否大于旧时间
     * </p>
     *
     * @param newDate
     * @param oldDate
     * @return
     */
    public static boolean isLaterThanEndtime(String newDate, String oldDate) {
        boolean b = false;
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date nd = df.parse(newDate);
            Date od = df.parse(oldDate);
            long newdate = nd.getTime();
            long olddate = od.getTime();
            if (newdate >= olddate) {
                b = true;
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return b;
    }

    /**
     * 实现时间的月份的相加
     * <p>
     * 日期加上多少个月份
     * </p>
     *
     * @param date  格式为yyyy-MM-dd
     * @param mouth 月份
     * @return
     */
    public static String addMouth(String date, int mouth) {
        Date date1 = null;
        if (date == null) {
            date1 = new Date();
        } else {
            date1 = parseStringMMToDate(date);
        }
        assert date1 != null;
        date1.setMonth(date1.getMonth() + mouth);
        SimpleDateFormat formatter = new SimpleDateFormat(FORMAT_M);
        return formatter.format(date1);
    }

    /**
     * 实现时间的月份的相加
     * <p>
     * 日期加上多少个月份
     * </p>
     *
     * @param date  格式为yyyy-MM-dd
     * @param mouth 月份
     * @return
     */
    public static String addMouthYMD(String date, int mouth) {
        long i = Long.parseLong(date);
        Date date1 = new Date(i);
        date1.setMonth(date1.getMonth() + mouth);
        return date1.getTime() + "";
    }

    /**
     * 实现时间的月份的相减
     * <p>
     * 日期减少多少个月份
     * </p>
     *
     * @param date  格式为yyyy-MM-dd
     * @param mouth 月份
     * @return
     */
    public static String subtractMouth(String date, int mouth) {
        Date date1 = null;
        if (date == null) {
            date1 = new Date();
        } else {
            date1 = parseStringMMToDate(date);
        }
        assert date1 != null;
        date1.setMonth(date1.getMonth() - mouth);
        SimpleDateFormat formatter = new SimpleDateFormat(FORMAT_M);
        return formatter.format(date1);
    }

    /**
     * 实现时间的月份的相减
     * <p>
     * 日期减少多少个月份
     * </p>
     *
     * @param date  格式为yyyy-MM-dd
     * @param mouth 月份
     * @return
     */
    public static Date reduceMouth(Date date, int mouth) {
        date.setMonth(date.getMonth() - mouth);
        return date;
    }

    /**
     * 实现时间的月份的相加
     * <p>
     * 日期加上多少个月份
     * </p>
     *
     * @param date  格式为yyyy-MM-dd
     * @param mouth 月份
     * @return
     */
    public static Date addMouth(Date date, int mouth) {
        Date date1 = new Date();
        date1.setMonth(date.getMonth() + mouth);
        return date1;
    }

    /**
     * 获取当前年份
     * <p>
     * 获取当前年份
     * </p>
     *
     * @return
     */
    public static int getCurrentYear() {
        Calendar c = Calendar.getInstance();
        return c.get(Calendar.YEAR);
    }

    /**
     * 根据月份得到相应的天数
     * <p>
     * 根据月份得到相应的天数
     * </p>
     *
     * @param month
     * @return
     */
    public static int getDaysByMonth(String year, String month) throws Exception {
        int days = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        Date d = sdf.parse(year + month);
        Calendar c = Calendar.getInstance();
        c.setTime(d);
        days = c.getActualMaximum(Calendar.DAY_OF_MONTH);
        return days;
    }
//	public static long getDays(String beginDay, String endDay) {
//		long day = 0;
//		SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
//		try {
//			Date date1 = ft.parse(endDay);
//			Date date2 = ft.parse(beginDay);
//			day = date1.getTime() - date2.getTime();
//			day = day / 1000 / 60 / 60 / 24;
//		} catch (ParseException e) {
//			e.printStackTrace();
//		}
//		return day;
//	}

    /**
     * 时间戳转为Date类型,只需要传入Object，转换出错时返回为空
     *
     * @param timeStamp
     * @return Date
     * @date 2018/7/29 上午10:14
     */
    public static Date timeStampToDate(Object timeStamp) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        if (timeStamp == null) {
            return date;
        }
        try {
            Long time = (Long) timeStamp;
            String d = format.format(time);
            date = format.parse(d);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return date;
    }

    /**
     * LocalDateTime转换为Date
     *
     * @param localDateTime
     */
    public static Date localDateTime2Date(LocalDateTime localDateTime) {
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt = localDateTime.atZone(zoneId);//Combines this date-time with a time-zone to create a  ZonedDateTime.
        return Date.from(zdt.toInstant());
    }

    /**
     * LocalDateTime转换为Date
     *
     * @param localDateTime
     */
    public static String localDateTime2DateWithFormat(LocalDateTime localDateTime, String pattern) {
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt = localDateTime.atZone(zoneId);//Combines this date-time with a time-zone to create a  ZonedDateTime.
        Date date = Date.from(zdt.toInstant());
        // 初始化时设置 日期和时间模式
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(new Date());
    }

    /**
     * 获取年的第一个月和最后一个月字符串
     *
     * @param str
     * @return
     */
    public static String getYearsFirstM(String str) {
        if (StringUtils.isNotEmpty(str)) {
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(str + "01");
            return stringBuffer + "";
        }
        return "";
    }

    public static String getYearsLastM(String str) {
        if (StringUtils.isNotEmpty(str)) {
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(str + "12");
            return stringBuffer + "";
        }
        return "";
    }

    public static String dateConvertion(String str) {
        Date parse = null;
        String dateString = "";
        try {
            parse = new SimpleDateFormat("yyyyMMdd").parse(str);
            dateString = new SimpleDateFormat("yyyy-MM-dd").format(parse);
        } catch (ParseException e) {
            dateString = null;
        }
        return dateString;
    }

    //
    public static String dateConvertionGov(String str) {
        Date parse = null;
        String dateString = "";
        try {
            parse = new SimpleDateFormat("yyyyMMdd").parse(str);
            dateString = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(parse);
        } catch (ParseException e) {
            dateString = null;
        }
        return dateString;
    }

    /**
     * * 在给定的日期加上或减去指定月份后的日期
     * *
     * * @param sourceDate 原始时间
     * * @param month      要调整的月份，向前为负数，向后为正数
     * * @return
     */
    public static String stepMonthString(Date sourceDate, int month) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(sourceDate);
        c.add(Calendar.MONTH, Integer.parseInt(month + ""));
        return df.format(c.getTime());
    }

    public static String getNowDate() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        return df.format(c.getTime());
    }

    /**
     * 将指定日期转换成yyyy-MM-dd格式的字符串
     *
     * @param
     * @return
     */
    public static String toString(Date date) {
        if (date == null) {
            return "";
        }
        return new SimpleDateFormat("yyyy-MM-dd").format(date);
    }

    /**
     * 将时间戳转换为时间
     */
    public static Date stampToDateYYYMM(String s) {
        long lt = new Long(s);
        Date date = new Date(lt);
        return date;
    }

    /**
     * 通过时间秒毫秒数判断两个时间的间隔
     *
     * @param date1
     * @param date2
     * @return
     */
    public static int differentDaysByMillisecond(Date date1, Date date2) {
        int days = (int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24));
        return days;
    }

    /**
     * * 在给定的日期加上或减去指定月份后的日期
     * *
     * * @param sourceDate 原始时间
     * * @param month      要调整的月份，向前为负数，向后为正数
     * * @return
     */
    public static Date stepMonth(Date sourceDate, int month) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(sourceDate);
        c.add(Calendar.MONTH, Integer.parseInt(month + ""));
//        return df.format(c.getTime());
        return c.getTime();
    }

    public static int isDateBeforeToMonth(String time1, String time2) {
        SimpleDateFormat df = new SimpleDateFormat(FORMAT_M, Locale.US);
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        try {
            c1.setTime(df.parse(time1));
            c2.setTime(df.parse(time2));
        } catch (ParseException e) {
            return 0;
        }
        int result = c1.compareTo(c2);
        return result;
    }


    /**
     * 格式化日期
     *
     * @param date 日期对象
     * @return String 日期字符串
     */
    public static String toMonth(Date date) {
        SimpleDateFormat f = new SimpleDateFormat("yyyyMM");
        return f.format(date);
    }

    /**
     * 时间戳和当前系统时间进行比较，两个时间的大小
     *
     * @return 0：time1（当天系统时间）相等time2（参数时间戳）；<br>
     * 1：time1大于time2；<br>
     * -1：time1小于time2；<br>
     */
    public static int isDateBefore(String time) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String time1 = df.format(new Date());
        Date date = TimeStapToDate(time);
        String time2 = df.format(date);
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        try {
            c1.setTime(df.parse(time1));
            c2.setTime(df.parse(time2));
        } catch (ParseException e) {
            return 0;
        }
        return c1.compareTo(c2);
    }

    /**
     * 时间戳转时间
     *
     * @param time
     * @return
     */
    public static Date TimeStapToDate(String time) {
        try {
            long longTimeStamp = new Long(time);
            return new Date(longTimeStamp);
        } catch (Exception e) {
            return null;
        }
    }

    public static String parseStringDate(String parseFormat) {
        SimpleDateFormat sdf = new SimpleDateFormat(parseFormat);
        return sdf.format(new Date());
    }

    /**
     * 给指定日期加上指定的天数
     *
     * @param
     * @param
     * @return
     */
    public static Date addDay(Date date, int count) {
        return new Date(date.getTime() + (86400000L * count));
    }

    /**
     * 增加天数
     *
     * @param addDay
     * @return
     */
    public static String addDay(int addDay) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.DATE, +addDay);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(cal.getTime());
    }

    /**
     * 获取下个月第一天
     *
     * @return
     */
    public static Date getNextMonth() throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_D);
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MONTH, +1);
        instance.set(Calendar.DAY_OF_MONTH, 1);
        String date = sdf.format(instance.getTime());
        return sdf.parse(date);
    }

    /**
     * 获取昨天是哪一天（yyyy-MM-dd）
     *
     * @return String yesterday
     */
    public static String getYesterday() {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, -24);
        String yesterday = dateFormat.format(calendar.getTime());
        return yesterday;
    }

    /**
     * 字符串转时间戳
     *
     * @param time
     * @example time="2019-04-19 00:00:00"
     **/
    public static Long getTimestamp(String time) {
        Long timestamp = null;
        try {
            timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return timestamp;
    }

    /**
     * 获取两个日期之间的所有日期
     *
     * @param startTime 开始日期
     * @param endTime   结束日期
     * @return
     */
    public static List<String> getDayBetween(String startTime, String endTime) {

        // 返回的日期集合
        List<String> days = new ArrayList<String>();

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date start = dateFormat.parse(startTime);
            Date end = dateFormat.parse(endTime);

            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);

            Calendar tempEnd = Calendar.getInstance();
            tempEnd.setTime(end);
            tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)
            while (tempStart.before(tempEnd)) {
                days.add(dateFormat.format(tempStart.getTime()));
                tempStart.add(Calendar.DAY_OF_YEAR, 1);
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }

        return days;
    }

    /**
     * 获取两个月份之间的所有月份(含跨年)
     *
     * @param minDate
     * @param maxDate
     * @return
     * @throws ParseException
     */
    public static List<String> getMonthBetween(String minDate, String maxDate) {
        ArrayList<String> result = new ArrayList<String>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");// 格式化为年月
        try {
            Calendar min = Calendar.getInstance();
            Calendar max = Calendar.getInstance();

            min.setTime(sdf.parse(minDate));
            min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

            max.setTime(sdf.parse(maxDate));
            max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

            Calendar curr = min;
            while (curr.before(max)) {
                result.add(sdf.format(curr.getTime()));
                curr.add(Calendar.MONTH, 1);
            }

            // 实现排序方法
            Collections.sort(result, new Comparator<Object>() {
                @Override
                public int compare(Object o1, Object o2) {
                    String str1 = (String) o1;
                    String str2 = (String) o2;
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
                    Date date1 = null;
                    Date date2 = null;
                    try {
                        date1 = format.parse(str1);
                        date2 = format.parse(str2);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                    if (date2.compareTo(date1) > 0) {
                        return -1;
                    }
                    return 1;
                }
            });
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取当前月份的最后一天
     */
    public static Date getLastDayOfMonth(Date date) {
        String timeYm = getTimeYm(date);//yyyyMM格式
        String year = timeYm.substring(0, 4);
        String moth = timeYm.substring(4, 6);
        Calendar cal = Calendar.getInstance();
        // 设置年份
        cal.set(Calendar.YEAR, Integer.parseInt(year));
        // 设置月份
        cal.set(Calendar.MONTH, Integer.parseInt(moth) - 1);
        // 获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DATE);
        // 设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        return cal.getTime();
        // 格式化日期
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//		return sdf.format(cal.getTime());
    }

    //获取两个日期之间的所有月份
    public static int getMonthSpace2(String startDate, String endDate) throws Exception {
        int monthCount = 0;

        Calendar startCalendar = Calendar.getInstance();
        Calendar endCalendar = Calendar.getInstance();

        startCalendar.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(startDate));
        endCalendar.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(endDate));

        int year = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);
        int month = endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);
        int day = Math.abs(endCalendar.get(Calendar.DATE) - startCalendar.get(Calendar.DATE));

        if (year == 0 && month == 0) {
            startCalendar.set(Calendar.DATE, 1);
            endCalendar.set(Calendar.DATE, 1);
            endCalendar.roll(Calendar.DATE, -1);
            if (day == (endCalendar.get(Calendar.DATE) - startCalendar.get(Calendar.DATE))) {
                monthCount = 1;// 两日期间满一个月
            } else {
                monthCount = 0;// 两日期间不足一个月
            }
        } else if (year != 0 && month == 0) {// 年份不同月份相同
            if (startCalendar.get(Calendar.DATE) < endCalendar.get(Calendar.DATE)) {// 两日期间的天数，小于等于当月
                monthCount = 1;
            }
            monthCount += year * 12 + month;
        } else {
            if (startCalendar.get(Calendar.DATE) >= endCalendar.get(Calendar.DATE)) {// 起始日期DATE 大于等于结束日期DATE
                monthCount = year * 12 + month;
            } else {
                monthCount = year * 12 + month + 1;
            }
        }

        return monthCount;
    }

    //获取两个日期相差年数
    public static int getYearDateDiff(String startDate, String endDate) {
        Calendar calStartTime = Calendar.getInstance(); //获取日历实例
        Calendar calEndTime = Calendar.getInstance();
        calStartTime.setTime(strTodate(startDate)); //字符串按照指定格式转化为日期
        calEndTime.setTime(strTodate(endDate));
        return calEndTime.get(Calendar.YEAR) - calStartTime.get(Calendar.YEAR);
    }

    //字符串按照指定格式转化为日期
    public static Date strTodate(String dateStr) {
        // 如果时间为空则默认当前时间
        Date date = null;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd");
        if (dateStr != null && !dateStr.equals("")) {
            String time = "";
            try {
                Date dateTwo = format.parse(dateStr);
                time = format.format(dateTwo);
                date = format.parse(time);
            } catch (ParseException e) {
                e.printStackTrace();
            }

        } else {
            String timeTwo = format.format(new Date());
            try {
                date = format.parse(timeTwo);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return date;
    }
}
